package com.zhida.smartcontrol.pagectrl.projectdetail.zonemanager;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.jay.tools.base.BaseDialogFragment;
import com.jay.tools.base.BaseFragment;
import com.jay.tools.recycler.OnItemClick;
import com.jay.tools.ui.Cbox;
import com.jay.tools.utils.EventBusUtils;
import com.jay.tools.utils.ResUtil;
import com.jay.tools.utils.SoftInputUtils;
import com.yanzhenjie.kalle.Kalle;
import com.zhida.smartcontrol.R;
import com.zhida.smartcontrol.common.Const;
import com.zhida.smartcontrol.common.bean.LampBean;
import com.zhida.smartcontrol.mvp.MVPBaseFragment;
import com.zhida.smartcontrol.dialog.deldevicedialog.DelDeviceDIalogFragment;
import com.zhida.smartcontrol.pagectrl.projectdetail.StartClickListener;
import com.zhida.smartcontrol.pagectrl.projectdetail.zonemanager.adddevice.AddDeviceFragment;
import com.zhida.smartcontrol.pagectrl.devicedetail.DeviceDetailFragment;
import com.zhida.smartcontrol.dialog.addqddialog.AddGroupEvent;
import com.zhida.smartcontrol.dialog.addqddialog.AddQdDialogFragment;
import com.zhida.smartcontrol.dialog.delqddialog.DelQdDialogFragment;
import com.zhida.smartcontrol.dialog.jieridialog.JieRiDialogFragment;
import com.zhida.smartcontrol.dialog.kgsjdialog.KgsjDialogFragment;
import com.zhida.smartcontrol.dialog.kzlxdialog.KzlxDialogFragment;
import com.zhida.smartcontrol.dialog.sjjzdialog.SjjzDialogFragment;
import com.zhida.smartcontrol.dialog.tdkgdialog.TdkgDialogFragment;
import com.zhida.smartcontrol.pagectrl.lampmanager.LampManagerFragment;
import com.zhida.smartcontrol.pagectrl.projectdetail.GroupBean;
import com.zhida.smartcontrol.common.bean.DeviceClassifyBean;
import com.zhida.smartcontrol.pop.DeviceClassifyPop;
import com.zhida.smartcontrol.utils.ClickUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;

/**
 * author: tanjianpei
 * date: 2019/10/11 011 11:47
 * description: 区段管理
 */
public class ZoneManagerFragment extends MVPBaseFragment<ZoneManagerContract.View, ZoneManagerPresenter> implements ZoneManagerContract.View {
    @BindView(R.id.recycler_left)
    RecyclerView mRViewLeft;
    @BindView(R.id.recycler_right)
    RecyclerView mRViewRight;
    @BindView(R.id.ll_add_jkq)
    LinearLayout mLLJkq;
    @BindView(R.id.ll_fenlei)
    LinearLayout mFLView;
    @BindView(R.id.tv_num)
    TextView mTvNum;
    @BindView(R.id.rl_empty)
    RelativeLayout mEmpty;
    @BindView(R.id.rl_bottom_group)
    RelativeLayout mBottomView;
    @BindView(R.id.cbox)
    Cbox mCbox;
    @BindViews({R.id.fl_kzlx, R.id.fl_jrms, R.id.fl_sjjz, R.id.fl_tdkg, R.id.fl_kgsj, R.id.fl_yxxm, R.id.fl_tcjx, R.id.fl_fuwei})
    List<FrameLayout> mFlBtns;
    @BindViews({R.id.tv_kzlx, R.id.tv_jrms, R.id.tv_sjjz, R.id.tv_tdkg, R.id.tv_kgsj, R.id.tv_yxxm, R.id.tv_tcjx, R.id.tv_fuwei})
    List<TextView> mTvBtns;
    @BindView(R.id.ll_quduan)
    LinearLayout mLLQuDuan;

    private int mWhite = -1;
    private int mBlue = -1;

    private QuduanAdapter mQdAdapter;
    private JkqAdapter mJkqAdapter;
    private DeviceClassifyPop mPop;

    private String mId;
    private String mProjectName;
    private String mGroupId;
    private String mGroupName;
    private String mSwitchType;
    private String mSwitchName;

    private boolean mNewSwitch = false;
    private StartClickListener listener;

    public ZoneManagerFragment setListener(StartClickListener listener) {
        this.listener = listener;
        return this;
    }

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    mHandler.postDelayed(refreshDevice, 5000);
                    break;
                case 1:
                    mHandler.removeCallbacks(refreshDevice);
                    break;
                case 2:
                    mHandler.post(refreshDevice);
                    break;
            }
        }
    };

    private Runnable refreshDevice = new Runnable() {
        @Override
        public void run() {
            mPresenter.requestDevice(mSwitchType, mGroupId, false);
        }
    };

    public static ZoneManagerFragment newInstance(String projectId, String projectName) {
        Bundle args = new Bundle();
        args.putString("id", projectId);
        args.putString("pName", projectName);
        ZoneManagerFragment fragment = new ZoneManagerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected Object getLayout() {
        return R.layout.fragment_zone_manager;
    }

    @Override
    protected void initLazy(Bundle savedInstanceState) {
        EventBusUtils.register(this);
        mLLQuDuan.setVisibility(View.GONE);

        mWhite = ResUtil.getColor(getProxyActivity(), R.color.c_FFFFFF);
        mBlue = ResUtil.getColor(getProxyActivity(), R.color.c_3862FF);

        initRecycler(mRViewLeft, 0.48f, R.color.c_EEEEEE, false, true);
        initRecycler(mRViewRight, 1, R.color.c_EEEEEE);

        mQdAdapter = new QuduanAdapter(null);
        mQdAdapter.bindToRecyclerView(mRViewLeft);

        mJkqAdapter = new JkqAdapter(null);
        mJkqAdapter.bindToRecyclerView(mRViewRight);

        mPop = new DeviceClassifyPop(getProxyActivity(), Const.O_CTRL);

        mTvNum.setVisibility(View.GONE);
        mLLJkq.setVisibility(View.GONE);
        mBottomView.setVisibility(View.GONE);
        mRViewRight.setVisibility(View.GONE);
        mEmpty.setVisibility(View.VISIBLE);

        mId = getArguments().getString("id");
        mProjectName = getArguments().getString("pName");
        mSwitchType = "0";
        mSwitchName = "智能控制器";

        mPresenter.requestGroup(mId);
    }

    public void exp() {
        mLLQuDuan.setVisibility(mLLQuDuan.isShown() ? View.GONE : View.VISIBLE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshGroup(AddGroupEvent add) {
        SoftInputUtils.hideSoftInput(getProxyActivity());
        mPresenter.requestGroup(mId);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshDevice(LampBean event) {
        mPresenter.requestDevice(mSwitchType, mGroupId, false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtils.unregister(this);
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        mHandler.obtainMessage(2).sendToTarget();
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        mHandler.obtainMessage(1).sendToTarget();
        Kalle.cancel("ZoneManagerPresenter");
    }

    @Override
    protected void initLazyEvents() {
        mCbox.setOnCboxClickListener(new Cbox.OnCboxClickListener() {
            @Override
            public void onCboxClick(View v) {
                Cbox box = (Cbox) v;
                for (LampBean datum : mJkqAdapter.getData()) {
                    datum.setCheck(box.isChecked());
                }
                mJkqAdapter.notifyDataSetChanged();
            }
        });
        mPop.setClickListener(new OnItemClick<Object>() {
            @Override
            public void onClick(Object info, int tag) {
                DeviceClassifyBean bean = (DeviceClassifyBean) info;
                mSwitchType = bean.getId();
                mSwitchName = bean.getName();
                // TODO
                mHandler.obtainMessage(1).sendToTarget();
                mHandler.obtainMessage(2).sendToTarget();
                mNewSwitch = true;
            }
        });
        mQdAdapter.setClickListener(new OnItemClick<GroupBean>() {
            @Override
            public void onClick(GroupBean info, int tag) {
                switch (tag) {
                    case 0: //编辑
                        AddQdDialogFragment.newInstance(info.getId(), info.getProjectBaseId(), info.getName())
                                .showDialog(getChildFragmentManager());
                        break;
                    case 1:
                        DelQdDialogFragment.newInstance(info.getId()).showDialog(getChildFragmentManager());
                        break;
                    case 3:
                        mGroupId = info.getId();
                        mGroupName = info.getName();
                        mHandler.obtainMessage(2).sendToTarget();
                        break;
                }
            }
        });
        mJkqAdapter.setClickListener(new OnItemClick<LampBean>() {
            @Override
            public void onClick(LampBean info, int tag) {
                switch (tag) {
                    case 0:
                        String code;
                        if (mSwitchType.equals(Const.ZIG_BEE_SINGLE + "")) {
                            code = info.getCode();//所属集控器的code
                        } else {
                            code = info.getCode();
                        }
                        listener.start(DeviceDetailFragment.newInstance(info.getId(), code, DeviceDetailFragment.CHANNEL_4, mSwitchType));
                        break;
                    case 1:
                        listener.start(LampManagerFragment.newInstance(info));
                        break;
                    case 2:
                        info.setGroupId(mGroupId);
                        info.setProjectName(mProjectName);
                        info.setGroupName(mGroupName);
                        info.setSwitchType(mSwitchType);
                        info.setSwitchTypeTxt(mSwitchName);
                        listener.start(AddDeviceFragment.newInstance(Const.TYPE_EDIT, info));
                        break;
                    case 3:
                        DelDeviceDIalogFragment.newInstance(info.getId()).showDialog(getChildFragmentManager());
                        break;
                }
            }
        });
    }

    @OnClick({R.id.fl_kzlx, R.id.fl_jrms, R.id.fl_sjjz, R.id.fl_tdkg, R.id.fl_kgsj,
            R.id.ll_add_quduan, R.id.ll_add_jkq, R.id.btn_add, R.id.ll_fenlei, R.id.fl_yxxm, R.id.fl_tcjx, R.id.fl_fuwei})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.ll_add_quduan:
                AddQdDialogFragment.newInstance("", mId, "").showDialog(getChildFragmentManager());
                break;
            case R.id.ll_add_jkq:
            case R.id.btn_add:
                LampBean bean = new LampBean();
                bean.setProjectName(mProjectName);
                bean.setGroupId(mGroupId);
                bean.setGroupName(mGroupName);
                listener.start(AddDeviceFragment.newInstance(Const.TYPE_ADD, bean));
                break;
            case R.id.ll_fenlei:
                mPop.showAsDropDown(mFLView, 0, 0);
                break;
            case R.id.fl_kzlx:
                clickBottomBtn(0);
                showDialog(KzlxDialogFragment.newInstance(mSwitchType, mJkqAdapter.getData()));
                break;
            case R.id.fl_jrms:
                clickBottomBtn(1);
                showDialog(JieRiDialogFragment.newInstance(mSwitchType, mJkqAdapter.getData()));
                break;
            case R.id.fl_sjjz:
                clickBottomBtn(2);
                showDialog(SjjzDialogFragment.newInstance(mSwitchType, mJkqAdapter.getData()));
                break;
            case R.id.fl_tdkg:
                clickBottomBtn(3);
                showDialog(TdkgDialogFragment.newInstance(mSwitchType, mJkqAdapter.getData()));
                break;
            case R.id.fl_kgsj:
                clickBottomBtn(4);
                showDialog(KgsjDialogFragment.newInstance(mSwitchType, mJkqAdapter.getData()));
                break;
            case R.id.fl_yxxm:
                clickBottomBtn(5);
                NormalDialog dialog = new NormalDialog(getContext());
                dialog.content("请选择运行/休眠模式?")
                        .style(NormalDialog.STYLE_TWO)//
                        .title("温馨提示")
                        .btnNum(3)
                        .btnTextColor(
                                R.color.c_666666, R.color.c_3862FF, R.color.c_FF4D62
                        )
                        .btnText("取消", "运行", "休眠")
                        .titleTextSize(23f)
                        .show();
                dialog.setOnBtnClickL((OnBtnClickL) () -> {
                            dialog.dismiss();
                            resetBtns();
                        }, (OnBtnClickL) () -> {
                            dialog.dismiss();
                            mPresenter.runningModel(mJkqAdapter.getData(), 2);
                            resetBtns();
                        },
                        (OnBtnClickL) () -> {
                            dialog.dismiss();
                            mPresenter.runningModel(mJkqAdapter.getData(), 3);
                            resetBtns();
                        }
                );
                break;
            case R.id.fl_tcjx:
                clickBottomBtn(6);
                NormalDialog dialog1 = new NormalDialog(getContext());
                dialog1.content("是否退出检修模式?")
                        .style(NormalDialog.STYLE_TWO)//
                        .title("温馨提示")
                        .btnNum(2)
                        .btnTextColor(
                                R.color.c_666666, R.color.c_666666
                        )
                        .btnText("是", "否")
                        .titleTextSize(23f)
                        .show();
                dialog1.setOnBtnClickL((OnBtnClickL) () -> {
                            dialog1.dismiss();
                            mPresenter.switchRepair(mJkqAdapter.getData(), 1);
                            resetBtns();
                        },
                        (OnBtnClickL) () -> {
                            dialog1.dismiss();
                            resetBtns();
                        }
                );
                break;
            case R.id.fl_fuwei:
                clickBottomBtn(7);
                NormalDialog dialog2 = new NormalDialog(getContext());
                dialog2.content("是否复位?")
                        .style(NormalDialog.STYLE_TWO)//
                        .title("温馨提示")
                        .btnNum(2)
                        .btnTextColor(
                                R.color.c_666666, R.color.c_666666
                        )
                        .btnText("是", "否")
                        .titleTextSize(23f)
                        .show();
                dialog2.setOnBtnClickL((OnBtnClickL) () -> {
                            dialog2.dismiss();
                            mPresenter.resetSwitch(mJkqAdapter.getData());
                            resetBtns();
                        },
                        (OnBtnClickL) () -> {
                            dialog2.dismiss();
                            resetBtns();
                        }
                );
                break;
        }
    }

    private void showDialog(BaseDialogFragment fragment) {
        mHandler.obtainMessage(1).sendToTarget();
        fragment.showDialog(getChildFragmentManager());
        fragment.setOnDestroyListener(new BaseDialogFragment.OnDestroyListener() {
            @Override
            public void onDestroy(Object object, boolean isChange) {
                resetBtns();
                mHandler.obtainMessage(2).sendToTarget();
            }
        });
    }

    private void clickBottomBtn(int id) {
        resetBtns();
        mFlBtns.get(id).setEnabled(false);
        mFlBtns.get(id).setBackgroundResource(R.drawable.db_button_1_1);
        mTvBtns.get(id).setTextColor(mWhite);
        mTvBtns.get(id).setBackgroundResource(android.R.color.transparent);
    }

    private void resetBtns() {
        for (FrameLayout mFlBtn : mFlBtns) {
            mFlBtn.setEnabled(true);
            mFlBtn.setBackgroundResource(R.drawable.db_button_2_1);
        }
        for (TextView mTvBtn : mTvBtns) {
            mTvBtn.setTextColor(mBlue);
            mTvBtn.setBackgroundResource(R.drawable.s_bg_search);
        }
    }

    @Override
    public void showGroup(List<GroupBean> groupList) {
        if (groupList.size() > 0) {
            mGroupId = groupList.get(0).getId();
            mGroupName = groupList.get(0).getName();
            mQdAdapter.replaceData(groupList);

            mPresenter.requestDevice(mSwitchType, mGroupId, true);
        }
    }

    @Override
    public void showLamp(List<LampBean> lampBeans) {
        if (mNewSwitch) {
            mNewSwitch = false;
        } else {
            for (LampBean lampBean : lampBeans) {
                for (LampBean datum : mJkqAdapter.getData()) {
                    if (datum.getId().equals(lampBean.getId())) {
                        lampBean.setCheck(datum.isCheck());
                    }
                }
            }
        }
        mJkqAdapter.replaceData(lampBeans);

        int num = lampBeans.size();
        mTvNum.setVisibility(View.VISIBLE);
        mTvNum.setText(mSwitchName + "：" + num);
        if (num == 0) {
            mLLJkq.setVisibility(View.GONE);
            mBottomView.setVisibility(View.GONE);
            mRViewRight.setVisibility(View.GONE);
            mEmpty.setVisibility(View.VISIBLE);
        } else {
            mBottomView.setVisibility(View.VISIBLE);
            mRViewRight.setVisibility(View.VISIBLE);
            mEmpty.setVisibility(View.GONE);
            mLLJkq.setVisibility(View.VISIBLE);
        }

        mHandler.obtainMessage(0).sendToTarget();

    }

}
